# from rest_framework.decorators import api_view
# from rest_framework.response import Response
# from .serializers import ForecastRequestSerializer
# from import_data.models import TrainMedicalData, ValMedicalData
# import pandas as pd
# import numpy as np
# from timesfm import TimesFm

# Инициализация модели и загрузка контрольной точки
# tfm = TimesFm(
#     context_len=512,
#     horizon_len=8,  # Горизонт прогноза
#     input_patch_len=32,
#     output_patch_len=128,
#     num_layers=20,
#     model_dims=1280,
#     backend='gpu',
# )

# tfm.load_from_checkpoint(repo_id="google/timesfm-1.0-200m")


# def forecast_studies_timesfm(data, column, steps=4, last_values=100):
#     input_series = data[column].values[-last_values:]
#     forecast_input = [input_series]
#     frequency_input = [1]

#     point_forecast, experimental_quantile_forecast = tfm.forecast(
#         forecast_input,
#         freq=frequency_input,
#     )
    
#     forecast_df = pd.DataFrame({
#         'ds': pd.date_range(start=data.index[-1] + pd.Timedelta(weeks=2), periods=steps, freq='W'),
#         'yhat': point_forecast[0][:steps].astype(int)
#     }).set_index('ds')
    
#     return forecast_df

# def calculate_error(actual, forecast):
#     return np.abs(1 - (forecast / actual))

# @api_view(['POST'])
# def forecast_view(request):
#     serializer = ForecastRequestSerializer(data=request.data)
#     if serializer.is_valid():
#         steps = serializer.validated_data['steps']

#         train_data = pd.DataFrame(list(TrainMedicalData.objects.all().values()))
#         train_data['date'] = pd.to_datetime(train_data['date'])
#         train_data.set_index('date', inplace=True)
#         val_data = pd.DataFrame(list(ValMedicalData.objects.all().values()))
#         val_data['date'] = pd.to_datetime(val_data['date'])
#         val_data.set_index('date', inplace=True)

#         forecasts = {}
#         errors = {}
#         for column in train_data.columns:
#             if column not in ['id', 'year', 'week_number']:
#                 forecast_df = forecast_studies_timesfm(train_data, column, steps)
#                 actual = val_data[column].iloc[:steps]
#                 forecasted = forecast_df['yhat'].values
#                 forecasts[column] = forecast_df['yhat'].tolist()
#                 # errors[column] = calculate_error(actual.values, forecasted).tolist()
        
#         formatted_forecasts = []
#         for week_index in range(steps):
#             week_forecast = {'week': week_index + 1}
#             for modality, values in forecasts.items():
#                 week_forecast[modality] = values[week_index]
#             formatted_forecasts.append(week_forecast)
        
#         return Response({'forecasts': formatted_forecasts, 'errors': errors})
#     else:
#         return Response(serializer.errors, status=400)



import os
import pandas as pd
import numpy as np
from prophet import Prophet
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import ForecastRequestSerializer
from .forecast import load_models, forecast_next_weeks, format_forecast_result
from import_data.models import TrainMedicalData, ValMedicalData

@api_view(['POST'])
def forecast_view(request):
    serializer = ForecastRequestSerializer(data=request.data)
    if serializer.is_valid():
        periods = serializer.validated_data['periods']

        train_data = pd.DataFrame(list(TrainMedicalData.objects.all().values()))
        train_data['date'] = pd.to_datetime(train_data['date'])
        train_data.set_index('date', inplace=True)

        # Загрузка моделей и конфигурации
        models, forecast_periods = load_models('config/config.json')

        # Прогнозирование
        forecasts = forecast_next_weeks(models, train_data, periods)

        # Формирование результата
        formatted_forecasts = format_forecast_result(forecasts)
        
        return Response({'forecasts': formatted_forecasts.to_dict(orient='records')})
    else:
        return Response(serializer.errors, status=400)